# -*- coding: utf-8 -*-
# @Time : 2022/1/5 13:50
# @Author : Limusen
# @File : base_page


import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from common.log_utils import logger
from common.config_utils import local_config


class BasePage:

    def __init__(self, driver):
        self.driver = driver  # driver

    def open_url(self, url):
        try:
            self.driver.get(url)
            logger.info("打开url：%s" % url)
        except Exception as e:
            logger.error("不能打开制定网站,原因是: %s" % e.__str__())

    def close_browser(self):
        self.driver.close()
        logger.info("关闭当前tab页签")

    def exit_driver(self):
        self.driver.quit()
        logger.info("退出浏览器")

    def set_window_max(self):
        self.driver.maximize_window()
        logger.info("浏览器最大化")

    def page_refresh(self):
        self.driver.refresh()
        logger.info("浏览器刷新")

    def get_title(self):
        value = self.driver.title
        logger.info("获取标题：%s" % value)
        return value

    def get_url(self):
        value = self.driver.current_url
        logger.info("获取url：%s" % value)
        return value

    def get_page_source(self):
        self.wait(1)
        source = self.driver.page_source
        logger.info("获取页面源码,用来检查是否包含某个元素：%s" % source)
        return source

    def back_up(self):
        self.driver.back()
        logger.info("返回上一页")

    def forward(self):
        self.driver.forward()
        logger.info("前进一页")

    def clear_input(self, element_info):
        element = self.find_element(element_info)
        element.clear()
        logger.info("清除内容输入框内容: %s" % element_info["locator_value"])

    # 　封装时间
    def wait(self, seconds=local_config.time_out):
        """
        固定等待--加入默认值，如果没有设置超时时间，则默认等待五秒钟

        :param seconds: 如果没有传入值则默认等待5秒钟
        """
        time.sleep(seconds)
        logger.info("休息一会儿 %s 秒钟~" % seconds)

    def implicitly_wait(self, seconds=local_config.time_out):
        """
        隐式等待--加入默认值，如果没有设置超时时间，则默认等待五秒钟

        :param seconds: 如果没有传入值则默认等待5秒钟
        """
        self.driver.implicitly_wait(seconds)
        logger.info("隐式等待个 %s 秒" % seconds)

    def find_element(self, element_info):
        """
        通过分离处理的元素识别字典信息，返回一个元素
        :param element_info: 元素信息，字典类型{}
        :return: element对象
        """
        try:
            locator_type = element_info["locator_type"]
            locator_value = element_info["locator_value"]
            locator_timeout = element_info["timeout"]

            if locator_type == "name":
                locator_type = By.NAME
            elif locator_type == "css":
                locator_type = By.CSS_SELECTOR
            elif locator_type == "xpath":
                locator_type = By.XPATH
            elif locator_type == "id":
                locator_type = By.ID
            elif locator_type == "class":
                locator_type = By.CLASS_NAME
            elif locator_type == "linktext":
                locator_type = By.LINK_TEXT
            elif locator_type == "partiallink":
                locator_type = By.PARTIAL_LINK_TEXT
            elif locator_type == "tag":
                locator_type = By.TAG_NAME
            element = WebDriverWait(self.driver, locator_timeout).until(
                lambda x: x.find_element(locator_type, locator_value))
            logger.info('[%s]元素识别成功' % element_info['element_name'])
        except Exception as e:
            logger.error("[%s]元素不能识别,原因是: %s" % (element_info['element_name'], e.__str__()))

        return element

    def get_text(self, element_info):
        element = self.find_element(element_info)
        try:
            text = element.text
            logger.info("获取文本信息：%s" % text)
            return text
        except Exception as e:
            logger.error("[%s]元素不能识别,原因是: %s" % (element_info['element_name'], e.__str__()))

    def input(self, element_info, inputs):
        """
        :param element_info: 元素信息，字典类型{}
        :param inputs: 输入参数
        """
        element = self.find_element(element_info)
        try:
            element.send_keys(inputs)
            logger.info("输入框输入内容：%s , 识别输入框：%s" % (inputs, element_info["locator_value"]))
        except Exception as e:
            logger.error("[%s]元素不能识别,原因是: %s" % (element_info['element_name'], e.__str__()))

    def click(self, element_info):
        """
        :param element_info: 元素信息，字典类型{}
        """
        element = self.find_element(element_info)
        try:
            element.click()
            logger.info("识别元素进行点击操作：%s" % element_info["locator_value"])
        except Exception as e:
            logger.error("[%s]元素不能识别,原因是: %s" % (element_info['element_name'], e.__str__()))


if __name__ == '__main__':
    chrome_options = Options()
    chrome_options.add_argument('no-sandbox')
    chrome_options.add_argument("headless")  # => 为Chrome配置无头模式
    chrome_options.add_argument('disable-dev-shm-usage')
    chrome_options.add_argument('lang=zh_CN.UTF-8')  # 设置默认编码为utf-8

    driver = webdriver.Chrome(options=chrome_options)
    db = BasePage(driver)
    db.open_url("http://www.baidu.com")
    driver.implicitly_wait(10)

    # 优化代码 读取excel中的数据
    element_info = {
        'input_text': {'element_name': '输入框', 'locator_type': 'xpath', 'locator_value': '//*[@id="kw"]',
                       'timeout': 5.0},
        'click_button': {'element_name': '点击按钮', 'locator_type': 'xpath', 'locator_value': '//*[@id="su"]',
                         'timeout': 5.0}}

    input_t = element_info['input_text']
    click_b = element_info['click_button']

    db.input(input_t, "测试一下")
    db.click(click_b)
